import { defineStore } from 'pinia'
// import { RequestMenu,RequestResource } from '@/api/index'
import axios from 'axios'
import router from '@/router'
// 加载@/views目录下所有的.vue单文件组件
const viteComponent = import.meta.glob('@/views/**/*.vue')
// console.log('viteComponent ',viteComponent)
/**
 * 动态权限菜单
 *   1. 调用菜单接口获取菜单列表数据
 *   2. 使用elementPlus组件库实现左侧菜单栏
 *   3. 格式化数据显示到菜单栏
 */
export const useMenuStore = defineStore('menu', {
    state: () => {
        return {
            menuList: [],
            resourceList:[]
        }
    },
    actions: {
        saveMenuList(roleId: number) {
            return new Promise( async(resolve,reject)=>{
                // 封装网络获取动态菜单
                // const data = await RequestMenu(roleId)
                const res = await axios({
                    method: 'get',
                    // url: 'http://localhost:3000/sys/menu',
                    // params:{
                    //     roleId
                    // }
                    url: 'http://localhost:3000/sys/operator_menu',
                    params:{
                        id:roleId
                    }
                })
                const { code, sysmenu } = res.data
                if (code === 1) {
                    // 1.保存网络菜单接口数据
                    this.menuList = sysmenu
                    // console.log(this.menuList)
                    // 2.格式化菜单数据
                    let routeMenuList = formateRouterMenu(sysmenu)
                    // console.log(routeMenuList);
                    // 3.添加动态路由,router对象
                    routeMenuList.forEach(route=>router.addRoute(route))
                }
                // // 获取资源权限
                // const resData = await RequestResource(roleId)
                // if(resData.resultCode === 1){
                //     this.resourceList = resData.resultInfo.resource
                // }
                const res2 = await axios({
                    method: 'get',
                    url: 'http://localhost:3000/sys/resource',
                    params:{
                        id:roleId
                    }
                })
                if(res2.data.code === 1){
                    this.resourceList = JSON.parse(res2.data.resource)
                }
                resolve('')
            })
            
        },
    },
    getters: {
        // 组件获取list值,直接store.list,不用写getters. 与vuex 中store.getters.list不同
        list: state => state.menuList,
    },
     // 使用该插件，开启数据缓存
	persist: {
		//这里存储默认使用的是session
		enabled: true,
		strategies: [
			{
				//key的名称
				key: 'menuKey',
				//更改默认存储，我更改为localStorage
				storage: localStorage,
				// 可以选择哪些进入local存储，这样就不用全部都进去存储了
				// 默认是全部进去存储
				// paths: ['menuList','resourceList'],
			},
		],
	},
})

/**
 * 格式化动态菜单
 * {                       {
 *     label:'',               label:'',
 *     path:''       =>        path:'/main_shop'
 *                             component:  Home
 *     children:[]             children:[
 *                                  {
 *                                      path:'/banner/list'
 *                                      component:  import('plateform/banner/list.vue')
 *                                  }
 *                              ]
 *
 * }                       }
 */
const formateRouterMenu = (menuList: any) => {
    let routeMenuList:any = [] // 格式化之后路由列表
    menuList.forEach((item: any) => {
        let children
        if (item.children && Array.isArray(item.children)) {
            children = formateRouterMenu(item.children)
        }
        const { id, label, iconCls, path, meta_title } = item
        //构造新的路由项route
        let newRoute = { id, label, iconCls, path, children ,meta:meta_title }
        //新的路由项增加component组件映射
        // 一级菜单路由直接返回Home组件
        if (path.indexOf('/main') !== -1) {
            newRoute = {
                ...newRoute,
                component: () => import('@/views/Home.vue'),
            }
        }else{
            //二级菜单路由返回对应路径组件
            newRoute = {
                ...newRoute,
                component: viteComponent[`/src/views/plateform${newRoute.path}.vue`]
            }
        }

        routeMenuList.push(newRoute)
    })
    return routeMenuList
}
